'use client'

import { useState, useEffect, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import { ArrowLeft, User, School, Calendar, Edit2, Save, X } from 'lucide-react'
import { Button } from '@/components/ui/button'

interface UserProfile {
  id: string
  username: string
  email: string
  school: string
  grade: number
  role: string
  created_at: string
}

export default function ProfilePage() {
  const router = useRouter()
  const [profile, setProfile] = useState<UserProfile | null>(null)
  const [loading, setLoading] = useState(true)
  const [editing, setEditing] = useState(false)
  const [editForm, setEditForm] = useState({
    username: '',
    school: '',
    grade: 1
  })

  const loadProfile = useCallback(async () => {
    try {
      // 从API获取当前用户信息
      const response = await fetch('/api/auth/me', {
        credentials: 'include'
      })

      if (!response.ok) {
        // 未登录，跳转到登录页
        router.push('/auth/login')
        return
      }

      const result = await response.json()

      if (result.success && result.data) {
        const userData = result.data
        const userProfile: UserProfile = {
          id: userData.id.toString(),
          username: userData.username,
          email: userData.email || '',
          school: userData.profile?.school || '',
          grade: userData.profile?.grade || 1,
          role: userData.role || 'student',
          created_at: userData.createdAt
        }

        setProfile(userProfile)
        setEditForm({
          username: userProfile.username,
          school: userProfile.school,
          grade: userProfile.grade
        })
      } else {
        router.push('/auth/login')
      }
    } catch (error) {
      console.error('加载用户资料错误:', error)
      router.push('/auth/login')
    } finally {
      setLoading(false)
    }
  }, [router])

  useEffect(() => {
    loadProfile()
  }, [loadProfile])

  async function handleSave() {
    if (!profile) return

    try {
      // 调用API更新用户资料
      const response = await fetch('/api/profile', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({
          username: editForm.username,
          school: editForm.school,
          grade: editForm.grade
        })
      })

      const result = await response.json()

      if (result.success) {
        await loadProfile()
        alert('个人资料已更新！')
        setEditing(false)
      } else {
        alert('更新失败：' + result.error)
      }
    } catch (error) {
      console.error('保存用户资料错误:', error)
      alert('保存失败，请重试')
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">加载中...</p>
        </div>
      </div>
    )
  }

  if (!profile) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="text-center">
          <p className="text-gray-600">无法加载用户资料</p>
          <Button onClick={() => router.push('/dashboard')} className="mt-4">
            返回首页
          </Button>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
      {/* 导航栏 */}
      <nav className="glassmorphism-nav sticky top-0 z-50 backdrop-blur-md bg-white/10 border-b border-white/20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center space-x-4">
              <button
                onClick={() => router.back()}
                className="p-2 rounded-lg hover:bg-white/20 transition-colors"
              >
                <ArrowLeft className="w-5 h-5 text-gray-600" />
              </button>
              <h1 className="text-2xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">
                个人资料
              </h1>
            </div>
          </div>
        </div>
      </nav>

      {/* 主要内容 */}
      <div className="max-w-4xl mx-auto px-4 py-8">
        <div className="glassmorphism-card p-8 rounded-2xl">
          <div className="flex items-center justify-between mb-8">
            <div className="flex items-center space-x-4">
              <div className="w-16 h-16 bg-gradient-to-r from-indigo-500 to-purple-600 rounded-full flex items-center justify-center">
                <User className="w-8 h-8 text-white" />
              </div>
              <div>
                <h2 className="text-2xl font-bold text-gray-800">{profile.username}</h2>
                <p className="text-gray-600">{profile.role === 'admin' ? '管理员' : '学生'}</p>
              </div>
            </div>

            {!editing ? (
              <Button
                onClick={() => setEditing(true)}
                variant="outline"
                className="flex items-center space-x-2"
              >
                <Edit2 className="w-4 h-4" />
                <span>编辑资料</span>
              </Button>
            ) : (
              <div className="flex space-x-2">
                <Button
                  onClick={handleSave}
                  variant="default"
                  className="flex items-center space-x-2"
                >
                  <Save className="w-4 h-4" />
                  <span>保存</span>
                </Button>
                <Button
                  onClick={() => {
                    setEditing(false)
                    setEditForm({
                      username: profile.username,
                      school: profile.school,
                      grade: profile.grade
                    })
                  }}
                  variant="outline"
                  className="flex items-center space-x-2"
                >
                  <X className="w-4 h-4" />
                  <span>取消</span>
                </Button>
              </div>
            )}
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* 基本信息 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold text-gray-800 flex items-center">
                <User className="w-5 h-5 mr-2" />
                基本信息
              </h3>

              <div className="space-y-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                  {editing ? (
                    <input
                      type="text"
                      value={editForm.username}
                      onChange={(e) => setEditForm({...editForm, username: e.target.value})}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                    />
                  ) : (
                    <p className="text-gray-900">{profile.username}</p>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                  <p className="text-gray-900">{profile.email}</p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">学校</label>
                  {editing ? (
                    <input
                      type="text"
                      value={editForm.school}
                      onChange={(e) => setEditForm({...editForm, school: e.target.value})}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                    />
                  ) : (
                    <p className="text-gray-900">{profile.school}</p>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">年级</label>
                  {editing ? (
                    <select
                      value={editForm.grade}
                      onChange={(e) => setEditForm({...editForm, grade: parseInt(e.target.value)})}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                    >
                      {[1,2,3,4,5,6,7,8,9].map(grade => (
                        <option key={grade} value={grade}>{grade}年级</option>
                      ))}
                    </select>
                  ) : (
                    <p className="text-gray-900">{profile.grade}年级</p>
                  )}
                </div>
              </div>
            </div>

            {/* 账户信息 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold text-gray-800 flex items-center">
                <Calendar className="w-5 h-5 mr-2" />
                账户信息
              </h3>

              <div className="space-y-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">注册时间</label>
                  <p className="text-gray-900">
                    {new Date(profile.created_at).toLocaleDateString('zh-CN')}
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">账户类型</label>
                  <p className="text-gray-900">
                    {profile.role === 'admin' ? '管理员账户' : '学生账户'}
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">用户ID</label>
                  <p className="text-gray-500 text-sm font-mono">{profile.id}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
